/**
 * Filename: ContactInviteActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/9 0:55
 */
package com.github.postsanf.yinian.activity;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.ContactGroupUserAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNContactUser;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.utils.CharacterParser;
import com.github.postsanf.yinian.utils.GetContactUser;
import com.github.postsanf.yinian.utils.PinyinComparator;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TrimNumberUtils;
import com.github.postsanf.yinian.widget.Sidebar;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class ContactInviteActivity extends BaseActivity implements SectionIndexer {
    private Toolbar mToolbar;
    private ListView sortListView;

    private EditText searchEditText;
    private ContactGroupUserAdapter contactUserAdapter;
    private LinearLayout titleLayout;
    private TextView title;
    private TextView tvNofriends;
    // 滚动记录标识
    private int lastFirstVisibleItem = -1;
    // 汉字转拼音
    private CharacterParser characterParser;
    private List<YNContactUser> SourceDateList;
    // 根据拼音排表
    private PinyinComparator pinyinComparator;
    private String gId;
    private YNAlbum curAlbum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_contact);
        initView();
    }

    private void initView() {
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        gId = String.valueOf(curAlbum.getGroupid());

        mToolbar = (Toolbar) findViewById(R.id.contact_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);

        // 获取本机联系人信息
        GetContactUser.GetContactUser(this);

        // Tab和匹配不到联系人时显示
        titleLayout = (LinearLayout) findViewById(R.id.title_layout);
        title = (TextView) this.findViewById(R.id.title_layout_catalog);
        tvNofriends = (TextView) this.findViewById(R.id.title_layout_no_friends);

        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        sortListView = (ListView) findViewById(R.id.lv_contact_user_list);

        sortListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        sortListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的item_cb实例的步骤
                ContactGroupUserAdapter.ViewHolder holder = (ContactGroupUserAdapter.ViewHolder) view.getTag();
                // 改变CheckBox的状态
                holder.item_cb.toggle();
                // 将CheckBox的选中状况记录下来
                contactUserAdapter.getIsSelected().put(Integer.parseInt(holder.setposition.getText().toString()), holder.item_cb.isChecked());
            }
        });

        SourceDateList = filledData(GetContactUser.lists);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        contactUserAdapter = new ContactGroupUserAdapter(SourceDateList, this);
        sortListView.setAdapter(contactUserAdapter);
        sortListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (SourceDateList.size() <= 0) {
                    return;
                }
                int section = getSectionForPosition(firstVisibleItem);
                int nextSection = getSectionForPosition(firstVisibleItem + 1);
                int nextSecPosition = getPositionForSection(+nextSection);
                if (firstVisibleItem != lastFirstVisibleItem) {
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                            .getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(SourceDateList.get(
                            getPositionForSection(section)).getNameLetters());
                }
                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });

        searchEditText = (EditText) findViewById(R.id.et_serch_text);

        // 根据输入框输入值的改变来过滤搜索
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // 这个时候不需要挤压效果 就把他隐藏掉
                titleLayout.setVisibility(View.GONE);
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    // 增加分类并为ListView填充数据
    private List<YNContactUser> filledData(List<YNContactUser> datas) {
        for (int i = 0; i < datas.size(); i++) {
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(datas.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            if (sortString.matches("[A-Z]")) {
                datas.get(i).setNameLetters(sortString.toUpperCase());
            } else {
                datas.get(i).setNameLetters("#");
            }
        }
        return datas;
    }

    // 根据输入数据过滤并更新ListView
    private void filterData(String filterStr) {
        List<YNContactUser> filterDateList = new ArrayList<YNContactUser>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
            tvNofriends.setVisibility(View.GONE);
        } else {
            filterDateList.clear();
            for (YNContactUser sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        contactUserAdapter.updateListView(filterDateList);
        if (filterDateList.size() == 0) {
            tvNofriends.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    //  根据ListView的当前位置获取分类的首字母的Char ascii值
    public int getSectionForPosition(int position) {
        if (SourceDateList.size() <= 0) {
            finish();
            return 0;
        }
        if(position<SourceDateList.size()){
            return SourceDateList.get(position).getNameLetters().charAt(0);
        }
        return 0;
    }

    //  根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
    public int getPositionForSection(int section) {
        for (int i = 0; i < SourceDateList.size(); i++) {
            String sortStr = SourceDateList.get(i).getNameLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    // 发送邀请
    private void doPost(String invateStr) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_PHONE_NUM, StringUtils.delLastTag(invateStr));
        mParam.put(CommonConstants.YNS_GROUP_ID, gId);
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynInvite))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resInvate = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resInvate.getCode())) {
                            finish();
                        } else {
                            showToast(CommonConstants.TIP_UNKNOW);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void checkeInfo() {
        String tempNum = "";
        String tempName = "";
        HashMap<Integer, Boolean> invateYes = contactUserAdapter.getIsSelected();
        for (int i = 0; i < invateYes.size(); i++) {
            if (invateYes.get(i)) {
                for (int j = 0; j < SourceDateList.size(); j++) {
                    if (SourceDateList.get(j).getId() == i) {
                        tempNum += TrimNumberUtils.trimTelNum(SourceDateList.get(j).getNumber()) + ",";
                        tempName += SourceDateList.get(j).getName() + ",";
                    }
                }
            }
        }
        if (tempNum.trim().length() <= 0) {
            showToast("请选择联系人");
            return;
        }
        doPost(tempNum);
        showToast("邀请已发出");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_invite, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.action_invite:
                checkeInfo();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
